<template>
	<div>
		<div class="text-center my-3">车辆配置</div>
		<van-form @submit="onSubmit">
			<van-cell-group inset>
				<van-field
					v-model="config.wifi.ssid"
					name="wifi"
					label="wifi名称"
					placeholder="wifi名称"
					:rules="[{ required: true, message: '请填写wifi名称' }]"
				/>
				<van-field
					v-model="config.wifi.pass"
					type="password"
					name="密码"
					label="密码"
					placeholder="密码"
					:rules="[{ required: true, message: '请填写密码' }]"
				/>
				<van-field v-model="car" is-link readonly label="车辆" placeholder="选择车辆" @click="showPicker = true" />
				<van-popup v-model:show="showPicker" round position="bottom">
					<van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
				</van-popup>
			</van-cell-group>
			<div style="margin: 16px">
				<van-button round block type="primary" native-type="submit"> 配置二维码生成 </van-button>
			</div>
		</van-form>

		<div class="text-center">
			<van-image v-show="showQr" class="w-64 h-64" :src="qrCode" />
		</div>
	</div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { closeToast, showLoadingToast, showToast } from "vant";
import { getCarConfigQrCode, getCarList } from "@/api/car.js";

const password = ref("");
const showPicker = ref(false);
const car = ref("");
const showQr = ref(false);
const qrCode = ref("");
//{"wifi":{"ssid":"DESKTOP-UHGO6O1","pass":"12345678"},"mqtt":{"clientId":"1212"}}
const config = ref({
	wifi: {
		ssid: "",
		pass: "",
	},
	mqtt: {
		clientId: "",
	},
});
const onSubmit = async (values) => {
	showLoadingToast("生成中...");
	const res = await getCarConfigQrCode(config.value);
	closeToast();
	if (res) {
		qrCode.value = res.data;
		showQr.value = true;
	}
};

const columns = ref([]);
const onConfirm = ({ selectedValues }) => {
	config.value.mqtt.clientId = selectedValues[0];
	showPicker.value = false;
	car.value = columns.value.find((item) => item.value === selectedValues[0]).text;
};

onMounted(() => {
	getCarList().then((res) => {
		if (res) {
			columns.value = res.data.map((item) => {
				return {
					text: item.name,
					value: item.id,
				};
			});
		}
	});
});
</script>

<style scoped></style>
